package org.itboys.mobile.service.mysql.weixin.wallet;

import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.service.lasted.SystemDictionaryService;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.reward.CooChargeRewardMapper;
import org.itboys.mobile.dao.reward.CooSellingRewardMapper;
import org.itboys.mobile.dao.wallet.CooWalletRecordMapper;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.reward.CooChargeReward;
import org.itboys.mobile.entity.mysql.reward.CooSellingReward;
import org.itboys.mobile.entity.mysql.wallet.CooWallet;
import org.itboys.mobile.entity.mysql.wallet.CooWalletRecord;
import org.itboys.mobile.service.mongo.weixin.member.SundayWeixinMemberService;
import org.itboys.mobile.service.mysql.web.reward.CooChargeRewardService;
import org.itboys.mongodb.service.BaseMySqlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 作者：zzq
 * 时间：2018/1/27
 * 描述：钱包
 */
@Service
public class CooWeixinWalletService extends BaseMySqlService<CooWallet>{
    @Autowired
    private SundayWeixinMemberService memberService;
    @Autowired
    private CooWalletRecordMapper walletRecordMapper;
    @Autowired
    private SystemDictionaryService dictionaryService;
    @Autowired
    private CooChargeRewardMapper chargeRewardMapper;
    @Autowired
    private CooSellingRewardMapper sellingRewardMapper;
    /**
     * 通过用户寻找消费卡钱包
     * @param memberId
     * @return
     */
    @Transactional
    public CooWallet findByMemberId(Long memberId ){
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("memberId", memberId);
        CooWallet wallet=null;
        List<CooWallet> wallets=super.select(param);
        if(ListUtil.isNotNull(wallets)){
            wallet=wallets.get(0);
        }else {
            wallet=new CooWallet(memberId);
            super.insert(wallet);
            wallet=super.find(wallet.getId());
        }
        return wallet;
    }

    @Transactional
    public void charge_callback(CooWalletRecord chargeRecord, String remark){
        Map<String,Object> param=new HashMap<String,Object>();
        BigDecimal zero = new BigDecimal("0.000");
        //修改充值记录
        chargeRecord.setRemark(remark);
        chargeRecord.setStatus(SundayCommonConstants.YES);

        walletRecordMapper.update(chargeRecord);
        logger.info("开始当前用户钱包修改");
        //修改钱包会员级别，可提现额度，业绩
        CooWallet chargeWallet=findByMemberId(chargeRecord.getMemberId());
        //修改钱包会员级别
        param.clear();
        List<CooChargeReward>  chargeRewards=chargeRewardMapper.select(param);
        SundayMember member=memberService.getById(chargeRecord.getMemberId());
        member.setIsAble(SundayCommonConstants.YES);
        for(CooChargeReward reward:chargeRewards){
            //根据配置金额相同
            if(chargeRecord.getAmount().compareTo(reward.getAmount())==0){

                member.setMemberLevel(reward.getMemberLevel());
               chargeWallet.setTotalLimit(reward.getLimitAmount());
               chargeWallet.setAbleLimit(reward.getLimitAmount());
               chargeWallet.setFrozenAmount(reward.getFrozenAmount());
               chargeWallet.setMemberLevel(reward.getMemberLevel());
               break;

            }
        }
        chargeWallet.setTotalAchievement(chargeWallet.getTotalAchievement().add(chargeRecord.getAmount()));
        super.update(chargeWallet);

      logger.info("当前用户钱包修改结束");

        logger.info("开始销售奖励分成");
        //推荐链ID集合。包含自己的ID
        logger.info("---------"+member.getSalesPath());
        List<String> salesIdsStr = Arrays.asList(member.getSalesPath().split("/"));
        List<Long> salesIds = new ArrayList<>();
        for(String idStr:salesIdsStr){
          if(StringUtils.isNotBlank(idStr)){
              logger.info("------salesIdStr====="+String.valueOf(idStr));
              salesIds.add(Long.valueOf(idStr));
          }
        }
        param.clear();
        param.put("memberIds",salesIds);
        List<CooWallet> salesWalltesNoSort =super.select(param);
        //2017年12月10日，重要，重要，重要。重新按照用户的推荐顺序排序钱包用户
        List<CooWallet> salesWaltes =new ArrayList<>();
        for(int i=0;i<salesIds.size();i++){
            //倒着取推荐链上的ID。例如：2256/2275/2295/2296 ，新的用户的在后面
            long salesId = salesIds.get(salesIds.size()-i-1);
            for(CooWallet walteNoSort:salesWalltesNoSort){
                if(salesId==walteNoSort.getMemberId().longValue()){
                    salesWaltes.add(walteNoSort);
                    break;
                }
            }
        }
        for(int i=0;i<salesWaltes.size();i++){
            CooWallet thisWallet=salesWaltes.get(i);
            if(thisWallet.getStatus()!=1){
                logger.info("----开始业绩分成----当前用户钱包被冻结--钱包ID"+thisWallet.getId());
                continue;
            }
            //第一代  和第三代  获得销售奖励
            if(i==1||i==3){
                logger.info("推荐人的id*********************************************"+thisWallet.getMemberId());
                logger.info("推荐人的可用余额*********************************************"+thisWallet.getAbleLimit());
                logger.info("推荐人的用户等级*********************************************"+thisWallet.getMemberLevel());
                BigDecimal scaleAmount=null;
                //普通卡
                if(chargeWallet.getMemberLevel()==SundayCommonConstants.wallet_member_level_putong){
                    scaleAmount=chargeRecord.getAmount().multiply(new BigDecimal("0.05"));
                }
                //银卡
                if(chargeWallet.getMemberLevel()==SundayCommonConstants.wallet_member_level_yin){
                    scaleAmount=chargeRecord.getAmount().multiply(new BigDecimal("0.08"));
                }
                //金卡
                if(chargeWallet.getMemberLevel()==SundayCommonConstants.wallet_member_level_jin){
                    scaleAmount=chargeRecord.getAmount().multiply(new BigDecimal("0.1"));
                }
                logger.info("折扣金额*************************************"+scaleAmount);
                //如果当前可用额度大于奖励   则加当前奖励    减少可用额度
                if(thisWallet.getAbleLimit().compareTo(scaleAmount)!=-1){
                    thisWallet.setAbleLimit(thisWallet.getAbleLimit().subtract(scaleAmount));
                    thisWallet.setTotalAmount(thisWallet.getTotalAmount().add(scaleAmount));
                    thisWallet.setCashAmount(thisWallet.getCashAmount().add(scaleAmount.multiply(new BigDecimal("0.7"))));
                    thisWallet.setScoreAmount(thisWallet.getScoreAmount().add(scaleAmount.multiply(new BigDecimal("0.3"))));
                    CooWalletRecord walletRecord =new CooWalletRecord(thisWallet.getMemberId(),  thisWallet.getId(), SundayCommonConstants.wallet_record_type_sales, "销售奖励来自："+member.getNickName()+"-第"+i+"代", thisWallet.getAbleLimit(),scaleAmount, SundayCommonConstants.YES);
                    walletRecordMapper.insert(walletRecord);
                    //如果可用额度小于当前的奖励则取完所有可用额度    作为总奖励
                }else if(thisWallet.getAbleLimit().compareTo(scaleAmount)==-1&&thisWallet.getAbleLimit().compareTo(zero)==1){
                    thisWallet.setAbleLimit(zero);
                    thisWallet.setTotalAmount(thisWallet.getTotalAmount().add(thisWallet.getAbleLimit()));
                    thisWallet.setCashAmount(thisWallet.getCashAmount().add(thisWallet.getAbleLimit().multiply(new BigDecimal("0.7"))));
                    thisWallet.setScoreAmount(thisWallet.getScoreAmount().add(thisWallet.getAbleLimit().multiply(new BigDecimal("0.3"))));
                    CooWalletRecord walletRecord =new CooWalletRecord(thisWallet.getMemberId(),  thisWallet.getId(), SundayCommonConstants.wallet_record_type_sales, "销售奖励来自："+member.getNickName()+"-折扣为：剩余额度", thisWallet.getAbleLimit(),scaleAmount, SundayCommonConstants.YES);
                    walletRecordMapper.insert(walletRecord);
                }
                super.update(thisWallet);
            }
        }

        logger.info("销售奖励分成结束");


        logger.info("开始全球业绩分红");

        param.clear();
        param.put("type",2);
        List<CooSellingReward>  qqRewards=sellingRewardMapper.select(param);
        BigDecimal starAchievement = null;
        for(CooSellingReward reward:qqRewards){
            starAchievement=reward.getNextAmount();
            break;
        }
        param.clear();
        param.put("startAchievement",starAchievement);
        List<CooWallet>  qqWallets=super.select(param);

        if(ListUtil.isNotNull(qqWallets)){
            List<Long> qqManagerIds=new ArrayList<>();
            for (CooWallet cooWallet :qqWallets) {
                qqManagerIds.add(cooWallet.getManagerId());
            }
            param.clear();
            param.put("managerIds",qqManagerIds);
            List<CooWallet> managerWallets=super.select(param);
            if(ListUtil.isNotNull(managerWallets)){
                for (CooWallet managerWallet :managerWallets) {
                    Integer dabiaoNumber=0;
                    BigDecimal scaleAmount=null;
                    BigDecimal newScale=new BigDecimal("0");
                    for (CooSellingReward reward :qqRewards) {

                            for (CooWallet wallet :qqWallets) {
                                if(LongUtil.isNotNull(wallet.getManagerId())&&wallet.getManagerId().longValue()==managerWallet.getMemberId().longValue()){
                                    if(wallet.getTotalAchievement().compareTo(reward.getAmount())!=-1){
                                        dabiaoNumber++;
                                    }
                                }
                            }
                        if(dabiaoNumber>=reward.getNumber()){
                            if(reward.getScale().compareTo(newScale)==1){
                                newScale=reward.getScale();
                            }
                        }

                    }


                    scaleAmount=chargeRecord.getAmount().multiply(newScale);

                    //如果当前可用额度大于奖励   则加当前奖励    减少可用额度
                    if(managerWallet.getAbleLimit().compareTo(scaleAmount)!=-1){
                        managerWallet.setAbleLimit(managerWallet.getAbleLimit().subtract(scaleAmount));
                        managerWallet.setTotalAmount(managerWallet.getTotalAmount().add(scaleAmount));
                        managerWallet.setCashAmount(managerWallet.getCashAmount().add(scaleAmount.multiply(new BigDecimal("0.7"))));
                        managerWallet.setScoreAmount(managerWallet.getScoreAmount().add(scaleAmount.multiply(new BigDecimal("0.3"))));
                        CooWalletRecord walletRecord =new CooWalletRecord(managerWallet.getMemberId(),  managerWallet.getId(), SundayCommonConstants.wallet_record_type_quanqiu, "全球奖励来自："+member.getNickName()+"折扣为："+newScale, managerWallet.getAbleLimit(),scaleAmount, SundayCommonConstants.YES);
                        walletRecordMapper.insert(walletRecord);
                        //如果可用额度小于当前的奖励则取完所有可用额度    作为总奖励
                    }else if(managerWallet.getAbleLimit().compareTo(scaleAmount)==-1&&managerWallet.getAbleLimit().compareTo(zero)==1){
                        managerWallet.setAbleLimit(zero);
                        managerWallet.setTotalAmount(managerWallet.getTotalAmount().add(managerWallet.getAbleLimit()));
                        managerWallet.setCashAmount(managerWallet.getCashAmount().add(managerWallet.getAbleLimit().multiply(new BigDecimal("0.7"))));
                        managerWallet.setScoreAmount(managerWallet.getScoreAmount().add(managerWallet.getAbleLimit().multiply(new BigDecimal("0.3"))));
                        CooWalletRecord walletRecord =new CooWalletRecord(managerWallet.getMemberId(),  managerWallet.getId(), SundayCommonConstants.wallet_record_type_quanqiu, "全球奖励来自："+member.getNickName()+"-折扣为：剩余额度", managerWallet.getAbleLimit(),scaleAmount, SundayCommonConstants.YES);
                        walletRecordMapper.insert(walletRecord);
                    }
                    super.update(managerWallet);
                }
            }


        }
        logger.info("全球业绩分红结束");



        logger.info("开始管理奖励分成");

        //推荐链ID集合。包含自己的ID
        logger.info("---------"+member.getManagerPath());
        List<String> managerIdsStr = Arrays.asList(member.getManagerPath().split("/"));
        List<Long> managerIds = new ArrayList<>();
        for(String tjIdStr:managerIdsStr){
          if(StringUtils.isNotBlank(tjIdStr)){
              logger.info("------managerIdStr====="+String.valueOf(tjIdStr));
              managerIds.add(Long.valueOf(tjIdStr));
          }
        }
        param.clear();
        param.put("memberIds",managerIds);
        List<CooWallet> managerWaltesNoSort =super.select(param);
        //2017年12月10日，重要，重要，重要。重新按照用户的推荐顺序排序钱包用户
        List<CooWallet> managerWaltes =new ArrayList<>();
        for(int i=0;i<managerIds.size();i++){
            //倒着取推荐链上的ID。例如：2256/2275/2295/2296 ，新的用户的在后面
            long tjId = managerIds.get(managerIds.size()-i-1);
            for(CooWallet tjWalteNoSort:managerWaltesNoSort){
                if(tjId==tjWalteNoSort.getMemberId().longValue()){
                    managerWaltes.add(tjWalteNoSort);
                    break;
                }
            }
        }


        for(int i=0;i<managerWaltes.size();i++){
            //本次循环的钱包
            CooWallet thisWallet = managerWaltes.get(i);
            BigDecimal scale=new BigDecimal("0.00");;//提成比例
            BigDecimal scaleAmount=null;
            //如果钱包被冻结。不参与业绩分成
            if(thisWallet.getStatus()!=1){
                logger.info("----开始业绩分成----当前用户钱包被冻结--钱包ID"+thisWallet.getId());
                continue;
            }
            //第一个是自己
            if(i==0){
                //thisWallet.setTotalAchievement(thisWallet.getTotalAchievement().add(chargeRecord.getAmount()));
                //推荐链的第二个人及以后，是自己的上级
            }else{
                //2017年12月13日
                //1，充值人的直接上级，不需要比对比例差，直接就是上级的极差
                if(i==1){
                    scale=thisWallet.getScale();
                    //2，充值人的直接上级以后的人，需要比对比例差
                }else{
                    scale=thisWallet.getScale().subtract(managerWaltes.get(i-1).getScale());
                    if(thisWallet.getScale().compareTo(zero)==1&&scale.compareTo(zero)!=1){
                        scale=new BigDecimal("0.01");
                    }
                }
                //只有折扣大于0时   才会产生管理奖
                if(scale.compareTo(zero)==1){
                    scaleAmount=scale.multiply(chargeRecord.getAmount());
                    //如果当前可用额度大于奖励   则加当前奖励    减少可用额度
                    if(thisWallet.getAbleLimit().compareTo(scaleAmount)!=-1){
                        thisWallet.setAbleLimit(thisWallet.getAbleLimit().subtract(scaleAmount));
                        thisWallet.setTotalAmount(thisWallet.getTotalAmount().add(scaleAmount));
                        thisWallet.setCashAmount(thisWallet.getCashAmount().add(scaleAmount.multiply(new BigDecimal("0.7"))));
                        thisWallet.setScoreAmount(thisWallet.getScoreAmount().add(scaleAmount.multiply(new BigDecimal("0.3"))));
                        CooWalletRecord walletRecord =new CooWalletRecord(thisWallet.getMemberId(),  thisWallet.getId(), SundayCommonConstants.wallet_record_type_manager, "管理奖励来自："+member.getNickName()+"-折扣为："+scale, thisWallet.getAbleLimit(),scaleAmount, SundayCommonConstants.YES);
                        walletRecordMapper.insert(walletRecord);
                        //如果可用额度小于当前的奖励则取完所有可用额度    作为总奖励
                    }else if(thisWallet.getAbleLimit().compareTo(scaleAmount)==-1&&thisWallet.getAbleLimit().compareTo(zero)==1){
                        thisWallet.setAbleLimit(zero);
                        thisWallet.setTotalAmount(thisWallet.getTotalAmount().add(thisWallet.getAbleLimit()));
                        thisWallet.setCashAmount(thisWallet.getCashAmount().add(thisWallet.getAbleLimit().multiply(new BigDecimal("0.7"))));
                        thisWallet.setScoreAmount(thisWallet.getScoreAmount().add(thisWallet.getAbleLimit().multiply(new BigDecimal("0.3"))));
                        CooWalletRecord walletRecord =new CooWalletRecord(thisWallet.getMemberId(),  thisWallet.getId(), SundayCommonConstants.wallet_record_type_manager, "管理奖励来自："+member.getNickName()+"-折扣为：剩余额度", thisWallet.getAbleLimit(),scaleAmount, SundayCommonConstants.YES);
                        walletRecordMapper.insert(walletRecord);
                    }
                }
                thisWallet.setTotalAchievement(thisWallet.getTotalAchievement().add(chargeRecord.getAmount()));


                logger.info("----业绩分成-用户ID="+thisWallet.getMemberId()+"-分成折扣="+scale+"分成金额="+scaleAmount+"增加业绩="+chargeRecord.getAmount());
            }

            super.update(thisWallet);





        }

        logger.info("管理奖励分成结束");

        logger.info("开始修改用户折扣");
        param.clear();
        param.put("type",1);
        List<CooSellingReward>  sellingRewards=sellingRewardMapper.select(param);
        param.clear();
        param.put("id in",managerIds);
        List<SundayMember> managerMembers = memberService.list(param);
        //查询的用户信息包括用户的第一级推荐的会员
        List<String> managerFirstIdsStr=new ArrayList<>();
        List<Long> managerFirstIds=new ArrayList<>();
        for(SundayMember managerMember:managerMembers){
            if(StringUtils.isNotEmpty(managerMember.getFirstPath())){
                managerFirstIdsStr.addAll(Arrays.asList(managerMember.getFirstPath().split("/")));
            }
        }
        //重新查询用户
        for(String managerFirstIdStr:managerFirstIdsStr){
            if(StringUtils.isNotBlank(managerFirstIdStr)){
                managerFirstIds.add(Long.valueOf(managerFirstIdStr));
            }
        }
        param.clear();
        //推荐链上的用户的第一级推荐人的钱包
        param.put("memberIds",managerFirstIds);
        List<CooWallet> managerFirstWallets = super.select(param);

        //先把第一梯队的推荐人信息写入到钱包中
        //for(CooWallet managerWallet:managerWaltes){
        for(int i=0;i<managerWaltes.size();i++){
            CooWallet managerWallet=managerWaltes.get(i);
                //如果是自己就跳过
                if(i==0){

                    continue;
                }

            List<CooWallet> firstWallets=new ArrayList<CooWallet>();
            for(SundayMember managerMember:managerMembers){
                if(LongUtil.isNotZreo(managerWallet.getMemberId())&&
                        managerWallet.getMemberId().longValue()==managerMember.getId()){
                    managerWallet.setFirstPath(managerMember.getFirstPath());
                    break;
                }
            }
            for (CooWallet firstWallet :managerFirstWallets) {
                if(LongUtil.isNotZreo(firstWallet.getManagerId())&&firstWallet.getManagerId().longValue()==managerWallet.getMemberId().longValue()){
                    firstWallets.add(firstWallet);
                }
            }
            managerWallet.setFirstWallets(firstWallets);

        }



        for(int i=0;i<managerWaltes.size();i++){
            //本次循环的钱包
            CooWallet thisWallet = managerWaltes.get(i);
            //如果是自己就跳过
            if(i==0){
                continue;
            }
            logger.info("修改用户折扣中---用户ID="+thisWallet.getMemberId());
            BigDecimal newScale=thisWallet.getScale();
            //通过循环奖项配置     得出业绩提成比例
            for(CooSellingReward reward:sellingRewards){
                Integer dabiaoNumber=0;
                //此次循环配置为普通级  则只判断该用户钱包总业绩是否达标
                if(reward.getLevel()==SundayCommonConstants.selling_reward_level_putong){
                    if(thisWallet.getTotalAchievement().compareTo(reward.getAmount())==1){
                        if(reward.getScale().compareTo(newScale)==1){
                            newScale=reward.getScale();
                        }
                    }
                }
                    //此次循环配置为星级   则该用户所有下级的用户钱包的数量和业绩是否达标
                    if(reward.getLevel()==SundayCommonConstants.selling_reward_level_star){
                        if(thisWallet.getTotalAchievement().compareTo(reward.getAmount())==1){
                            if(reward.getScale().compareTo(newScale)==1){
                                newScale=reward.getScale();
                            }
                        }
                        if(ListUtil.isNotNull(thisWallet.getFirstWallets())){
                            //循环下级钱包    统计下级达标数
                            for (CooWallet firstWallet :thisWallet.getFirstWallets()) {
                                if(firstWallet.getTotalAchievement().compareTo(reward.getNextAmount())==1){
                                    dabiaoNumber++;
                                }
                            }
                        }
                        if(dabiaoNumber>=reward.getNumber()){
                            if(reward.getScale().compareTo(newScale)==1){
                                newScale=reward.getScale();
                            }
                        }
                    }
            }
            logger.info("新的折扣为********************************************"+newScale);
            thisWallet.setScale(newScale);
            super.update(thisWallet);
        }

        logger.info("修改用户折扣结束");


        //最后更新用户等级   防止事物性问题
        memberService.updateExceptEmpty(member.getId(),member);
    }
}
